﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml.Linq;
using GalaSoft.MvvmLight;
using Mutzl.Samples.VideoApp.Controls;
using Windows.Data.Html;
using Windows.Web.Syndication;
using System.Linq;

namespace Mutzl.Samples.VideoApp.YouTube.Model
{
    public class Video : ObservableObject, IResizable
    {

        private string _id;
        public string Id
        {
            get { return _id; }
            set
            {
                if (_id == value) return;
                _id = value;
                RaisePropertyChanged(() => Id);
            }
        }

        private string _title;
        public string Title
        {
            get { return _title; }
            set
            {
                if (_title == value) return;
                _title = value;
                RaisePropertyChanged(() => Title);
            }
        }

        private string _description;
        public string Description
        {
            get { return _description; }
            set
            {
                if (_description == value) return;
                _description = value;
                RaisePropertyChanged(() => Description);
            }
        }

        private string _thumbNailPath;
        public string ThumbNailPath
        {
            get { return _thumbNailPath; }
            set
            {
                if (_thumbNailPath == value) return;
                _thumbNailPath = value;
                RaisePropertyChanged(() => ThumbNailPath);
            }
        }

        private string _posterPath;
        public string PosterPath
        {
            get { return _posterPath; }
            set
            {
                if (_posterPath == value) return;
                _posterPath = value;
                RaisePropertyChanged(() => PosterPath);
            }
        }
        
        private Uri _link;
        public Uri Link
        {
            get { return _link; }
            set
            {
                if (_link == value) return;
                _link = value;
                RaisePropertyChanged(() => Link);
            }
        }

        private TimeSpan _duration;
        public TimeSpan Duration
        {
            get { return _duration; }
            set
            {
                if (_duration == value) return;
                _duration = value;
                RaisePropertyChanged(() => Duration);
            }
        }

        private string _author;
        public string Author
        {
            get { return _author; }
            set
            {
                if (_author == value) return;
                _author = value;
                RaisePropertyChanged(() => Author);
            }
        }

        private DateTime _date;
        public DateTime Date
        {
            get { return _date; }
            set
            {
                if (_date == value) return;
                _date = value;
                RaisePropertyChanged(() => Date);
            }
        }

        private List<string> _categories;
        public List<string> Categories
        {
            get { return _categories; }
            set
            {
                if (_categories == value) return;
                _categories = value;
                RaisePropertyChanged(() => Categories);
            }
        }

        //Todo: C01. weitere Properties je nach Bedarf hinzufügen (Speaker, Author, Date, ...)

        //Implementierung von IResizable
        //Width und Height für die variable GridView in der Hauptansicht
        public int Width { get; set; }
        public int Height { get; set; }

        public async static Task<IEnumerable<Video>> GetVideosAsync(string rssUri)
        {
            return await GetVideosAsync(new Uri(rssUri, UriKind.Absolute));
        }

        public async static Task<IEnumerable<Video>> GetVideosAsync(Uri rssUri)
        {
            try
            {
                var client = new SyndicationClient();

                SyndicationFeed feed = await client.RetrieveFeedAsync(rssUri);


                var videos = new List<Video>();

                foreach (var item in feed.Items)
                {

                    try
                    {
                        // Todo: C04. Hier gegebenenfalls Parsing des RSS anpassen.
                        // Daten-Sample siehe \YouTubeRss.xml

                        var group = item.ElementExtensions.SingleOrDefault(e => e.NodeName == "group");

                        var video = new Video();

                        // Objectinitializer wäre natürlich hübscher, Zuweisung zu Properties ist aber leichter zu debuggen.               
                        video.Id = item.Id.Substring(item.Id.LastIndexOf('/') + 1);
                        video.Title = item.Title.Text;
                        video.Description = HtmlUtilities.ConvertToText(item.Summary.Text);

                        video.Duration =
                            TimeSpan.FromSeconds(int.Parse(group
                                                               .ElementExtensions.SingleOrDefault(e => e.NodeName == "duration")
                                                               .AttributeExtensions.SingleOrDefault(a => a.Name == "seconds").Value));
                        video.Link = item.Links.FirstOrDefault().Uri;
                        video.Date = item.PublishedDate.DateTime;
                        video.Author = item.Authors.FirstOrDefault().NodeValue;
                        video.Categories = item.Categories.Select(c => c.Term).ToList();
                        video.ThumbNailPath = group.ElementExtensions.SingleOrDefault(e => e.NodeName == "thumbnail"
                            && e.AttributeExtensions.SingleOrDefault(a => a.Name == "width").Value == "480").AttributeExtensions.SingleOrDefault(a => a.Name == "url").Value;
                        video.PosterPath = video.ThumbNailPath;

                        videos.Add(video);

                    }
                    catch
                    {
                    }
                }

                return videos;
            }
            catch
            {
                return null;
            }
        }

        // wird im Design-Modus geladen, damit Layout in Blend und Visual Studio sichtbar ist.
        public static Video CreateDesignVideo()
        {
            return new Video
            {
                Id = "CjxkXNC31Z4",
                Title = "Light Line",
                Description = HtmlUtilities.ConvertToText(@"Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."),
                Duration = TimeSpan.FromSeconds(311),
                Link = new Uri("http://www.youtube.com/watch?v=CjxkXNC31Z4&amp;feature=youtube_gdata"),
                Date = DateTime.Parse("Wed, 17 Oct 2012 15:01:34 +0000"),
                Author = "Jean-Baptiste CHANDELIER",
                Categories = new List<string>
                                 {
                                    "Sports",
                                    "http://gdata.youtube.com/schemas/2007#video",
                                 },
                ThumbNailPath = "ms-appx:///Assets/demo_youtube.jpg",
            };
        }


    }
}
